import request from '../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoGroupList: [],//导航标签数据
    navId: '',//导航标识
    videoList: '',//视频列表数据
    vid: '',//播放视频标识
    videoContext: null,//上一个播放的video实例对象
    videoId: '',//视频id标识
    videoUpdateTime: [],//记录video播放时长
    isTriggered: false,//标识下拉刷新是否被触发
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    //获取导航数据
    this.getVideoGroupListData();
  },
  //获取导航数据
  async getVideoGroupListData(){
    let videoGroupListData = await request('/video/group/list')
    this.setData({
      videoGroupList: videoGroupListData.data.slice(0,14),
      navId: videoGroupListData.data[0].id
    })
    //获取视频列表数据
    this.getVideoList(this.data.navId);
  },
  //获取视频数据
  async getVideoList(navId){
    // let videoListData = await request('/video/group',{id: navId});
    // let index = 0;
    // let videoList = videoListData.datas.map(item=>{
    //   item.id = index++;
    //   return item
    // })
    // this.setData({
    //   videoList
    // })
    
    let result = await request('/video/group',{id: navId});

    // let videoListData=await Promise.all(result.datas.map(async item=>{
    let videoListData=await Promise.all(result.datas.splice(0,2).map(async item=>{
      item.id=item.data.vid
      let result=await request('/video/url',{id:item.id})
      item.url=result.urls[0].url
      return item
    }))
    //关闭消息提示框
    wx.hideLoading();

    this.setData({
      videoList:videoListData,
      isTriggered: false
    })
  },
  //点击切换导航的回调
  changeNav(event){
    // let navId = event.currentTarget.id;
    let navId = event.currentTarget.dataset.id;
    this.setData({
      navId: navId*1,
      videoList: []
    })
    // 显示正在加载
    wx.showLoading({
      title:'正在加载'
    })
    //获取视频列表数据
    this.getVideoList(this.data.navId);
  },

  //点击播放、继续播放的回调
  handlePlay(event){
    /*
      问题： 多个视频同时播放的问题
    * 需求：
    *   1. 在点击播放的事件中需要找到上一个播放的视频
    *   2. 在播放新的视频之前关闭上一个正在播放的视频
    * 关键：
    *   1. 如何找到上一个视频的实例对象
    *   2. 如何确认点击播放的视频和正在播放的视频不是同一个视频
    * 单例模式：
    *   1. 需要创建多个对象的场景下，通过一个变量接收，始终保持只有一个对象，
    *   2. 节省内存空间
    * */
    let vid = event.currentTarget.id;
    // 关闭上一个播放的视频
    // this.vid !== vid && this.videoContext && this.videoContext.stop();
    if(this.vid !== vid && this.videoContext){
      this.videoContext.stop();
    }
    this.vid = vid;
    this.setData({
      videoId: vid
    })
    // 创建控制video标签的实例对象
    this.videoContext = wx.createVideoContext(vid);

    let {videoUpdateTime} = this.data;
    let videoItem = videoUpdateTime.find(item=>item.vid === vid);
    if(videoItem){
      this.videoContext.seek(videoItem.currentTime);
    }
    this.videoContext.play();
  },
  // 监听视频播放进度的回调
  handleTimeUpdate(event){
    let videoTimeObj = {vid: event.currentTarget.id, currentTime: event.detail.currentTime};
    let {videoUpdateTime} = this.data;
    /*
     * 思路： 判断记录播放时长的videoUpdateTime数组中是否有当前视频的播放记录
     *   1. 如果有，在原有的播放记录中修改播放时间为当前的播放时间
     *   2. 如果没有，需要在数组中添加当前视频的播放对象
     *
     * */
    let videoItem = videoUpdateTime.find(item=>item.vid === videoTimeObj.vid);
    if(videoItem){//之前有
      videoItem.currentTime = videoTimeObj.currentTime;
    }else{//之前没有
      videoUpdateTime.push(videoTimeObj);
    }
    // 更新videoUpdateTime的状态
    this.setData({
      videoUpdateTime
    })
  },
  // 视频播放结束的回调
  handleEnded(event){
    // 移除记录播放时长数组中当前视频的对象
    let {videoUpdateTime} = this.data;
    videoUpdateTime.splice(videoUpdateTime.findIndex(item => item.vid === event.currentTarget.id), 1);
    this.setData({
      videoUpdateTime
    })
  },
  //自定义下拉刷新的回调：scroll-view
  handleRefresher(){
    // console.log('刷新')
    // 再次发请求，获取最新的视频列表数据
    this.getVideoList(this.data.navId);
  },
  // 自定义上拉触底的回调 scroll-view
  handelToLower(){
    // 数据分页：1.后端分页，2.前端分页
    let newVideoList = [
      {
          "type": 1,
          "displayed": false,
          "alg": "onlineHotGroup",
          "extAlg": null,
          "data": {
              "alg": "onlineHotGroup",
              "scm": "1.music-video-timeline.video_timeline.video.181017.-295043608",
              "threadId": "R_VI_62_9584673D259B790139702A4A05C25FA1",
              "coverUrl": "https://p2.music.126.net/RAzl9KaQ17wU7o5oK95y-w==/109951163573119442.jpg",
              "height": 720,
              "width": 960,
              "title": "迈克尔·杰克逊《Dangerous》经典现场，每个动作帅到极致",
              "description": "迈克尔·杰克逊《Dangerous》1997年的经典演唱会现场版，每个动作都帅到极致！",
              "commentCount": 713,
              "shareCount": 1436,
              "resolutions": [
                  {
                      "resolution": 240,
                      "size": 28966465
                  },
                  {
                      "resolution": 480,
                      "size": 42308339
                  },
                  {
                      "resolution": 720,
                      "size": 67599163
                  }
              ],
              "creator": {
                  "defaultAvatar": false,
                  "province": 340000,
                  "authStatus": 0,
                  "followed": false,
                  "avatarUrl": "http://p1.music.126.net/C6VID_CReqmt8ETsUWaYTQ==/18499283139231828.jpg",
                  "accountStatus": 0,
                  "gender": 0,
                  "city": 340100,
                  "birthday": -2209017600000,
                  "userId": 479954154,
                  "userType": 207,
                  "nickname": "音乐诊疗室",
                  "signature": "当我坐在那架破旧古钢琴旁边的时候，我对最幸福的国王也不羡慕。（合作推广请私信，或者+V信：mjs927721）",
                  "description": "",
                  "detailDescription": "",
                  "avatarImgId": 18499283139231828,
                  "backgroundImgId": 1364493978647983,
                  "backgroundUrl": "http://p1.music.126.net/i4J_uvH-pb4sYMsh4fgQAA==/1364493978647983.jpg",
                  "authority": 0,
                  "mutual": false,
                  "expertTags": null,
                  "experts": {
                      "1": "音乐视频达人",
                      "2": "音乐资讯达人"
                  },
                  "djStatus": 0,
                  "vipType": 11,
                  "remarkName": null,
                  "backgroundImgIdStr": "1364493978647983",
                  "avatarImgIdStr": "18499283139231828"
              },
              "urlInfo": null,
              "videoGroup": [
                  {
                      "id": 58100,
                      "name": "现场",
                      "alg": null
                  },
                  {
                      "id": 57106,
                      "name": "欧美现场",
                      "alg": null
                  },
                  {
                      "id": 57108,
                      "name": "流行现场",
                      "alg": null
                  },
                  {
                      "id": 1100,
                      "name": "音乐现场",
                      "alg": null
                  },
                  {
                      "id": 5100,
                      "name": "音乐",
                      "alg": null
                  }
              ],
              "previewUrl": "http://vodkgeyttp9.vod.126.net/vodkgeyttp8/preview_1357854805_Dz8b2RQt.webp?wsSecret=6b618508beb628b0929f960eb427b0b0&wsTime=1677409840",
              "previewDurationms": 4000,
              "hasRelatedGameAd": false,
              "markTypes": null,
              "relateSong": [
                  {
                      "name": "Dangerous",
                      "id": 21178422,
                      "pst": 0,
                      "t": 0,
                      "ar": [
                          {
                              "id": 38853,
                              "name": "Michael Jackson",
                              "tns": [],
                              "alias": []
                          }
                      ],
                      "alia": [],
                      "pop": 100,
                      "st": 0,
                      "rt": "600902000006888029",
                      "fee": 1,
                      "v": 38,
                      "crbt": null,
                      "cf": "",
                      "al": {
                          "id": 1958224,
                          "name": "Dangerous",
                          "picUrl": "http://p4.music.126.net/0GwTY8utXBiMHovPwtwS1Q==/109951165965092927.jpg",
                          "tns": [],
                          "pic_str": "109951165965092927",
                          "pic": 109951165965092930
                      },
                      "dt": 417776,
                      "h": {
                          "br": 320000,
                          "fid": 0,
                          "size": 16712142,
                          "vd": -50594
                      },
                      "m": {
                          "br": 192000,
                          "fid": 0,
                          "size": 10027302,
                          "vd": -48056
                      },
                      "l": {
                          "br": 128000,
                          "fid": 0,
                          "size": 6684883,
                          "vd": -46706
                      },
                      "a": null,
                      "cd": "1",
                      "no": 14,
                      "rtUrl": null,
                      "ftype": 0,
                      "rtUrls": [],
                      "djId": 0,
                      "copyright": 1,
                      "s_id": 0,
                      "rtype": 0,
                      "rurl": null,
                      "cp": 7001,
                      "mv": 407055,
                      "mst": 9,
                      "publishTime": 1362067200000,
                      "privilege": {
                          "id": 21178422,
                          "fee": 1,
                          "payed": 0,
                          "st": 0,
                          "pl": 0,
                          "dl": 0,
                          "sp": 0,
                          "cp": 0,
                          "subp": 0,
                          "cs": false,
                          "maxbr": 320000,
                          "fl": 0,
                          "toast": false,
                          "flag": 4,
                          "preSell": false
                      }
                  }
              ],
              "relatedInfo": null,
              "videoUserLiveInfo": null,
              "vid": "9584673D259B790139702A4A05C25FA1",
              "durationms": 246842,
              "playTime": 667076,
              "praisedCount": 4543,
              "praised": false,
              "subscribed": false
          },
          "id": "9584673D259B790139702A4A05C25FA1",
          "url": "http://vodkgeyttp9.vod.126.net/vodkgeyttp8/L1AMTp2a_1357854805_shd.mp4?ts=1677413441&rid=D180765541F90BA045005389510FCD97&rl=3&rs=ufqJgMafpaEDKsLYFDHRkIaUSrUAGlsp&sign=470a582d42de89c521f58a14454dfa44&ext=%2FOIbZbadGXOxUwEwUpe5lcOmKcsflJQ4uu362YdMwFHsNDNEt%2BpGMHpHJ9AenEi7IfMhT1dfaNX8Wl6ZwhSB9lMTZXCRcVcDU7YyLbfQQpJ5kV4iRio7mkcQIL2f6MsgqK4t3o0rYXv5%2BxoSDgF%2FFExEmZ2e5qJ5K7vtsrY5z9Y%2FUHPwE%2FZijxwViemCtK0FiwJ%2BoUatcV2hZPUon53U65k27uaPvGlSTD4QExdF%2FAhRUth4elYKL1gVylOFapOm"
      },
      {
          "type": 1,
          "displayed": false,
          "alg": "onlineHotGroup",
          "extAlg": null,
          "data": {
              "alg": "onlineHotGroup",
              "scm": "1.music-video-timeline.video_timeline.video.181017.-295043608",
              "threadId": "R_VI_62_8F9BB19518CBFA14708BD4641DBB7A9A",
              "coverUrl": "https://p2.music.126.net/K_venVylnIiwcGhIDdNzXA==/109951163572792521.jpg",
              "height": 720,
              "width": 1280,
              "title": "被演技耽误的歌手古天乐开口唱歌，郑秀文台上尖叫，观众台下欢呼",
              "description": "Sammi演唱完《我们的主题曲》，演唱会压轴嘉宾古天乐出场，古仔被Sammi玩坏了，呼啦啦啦啦。要求唱歌，被演技耽误的歌手古天乐开口唱歌，演唱哥哥的歌曲《当年情》，郑秀文台上尖叫，观众台下欢呼。",
              "commentCount": 2635,
              "shareCount": 2735,
              "resolutions": [
                  {
                      "resolution": 240,
                      "size": 49498335
                  },
                  {
                      "resolution": 480,
                      "size": 70374345
                  },
                  {
                      "resolution": 720,
                      "size": 111985504
                  }
              ],
              "creator": {
                  "defaultAvatar": false,
                  "province": 340000,
                  "authStatus": 0,
                  "followed": false,
                  "avatarUrl": "http://p1.music.126.net/Vh15ofgGmgSGhqO5VoswOQ==/109951167235930856.jpg",
                  "accountStatus": 0,
                  "gender": 1,
                  "city": 340100,
                  "birthday": 841507200000,
                  "userId": 268678989,
                  "userType": 200,
                  "nickname": "随身音乐厅",
                  "signature": "音乐的魅力，在于人的精神与音乐的共鸣。",
                  "description": "",
                  "detailDescription": "",
                  "avatarImgId": 109951167235930850,
                  "backgroundImgId": 109951165395733630,
                  "backgroundUrl": "http://p1.music.126.net/JoV68ORMXbVRqYMDNp28GA==/109951165395733633.jpg",
                  "authority": 0,
                  "mutual": false,
                  "expertTags": [
                      "华语"
                  ],
                  "experts": {
                      "1": "音乐视频达人",
                      "2": "生活图文达人"
                  },
                  "djStatus": 10,
                  "vipType": 11,
                  "remarkName": null,
                  "backgroundImgIdStr": "109951165395733633",
                  "avatarImgIdStr": "109951167235930856"
              },
              "urlInfo": null,
              "videoGroup": [
                  {
                      "id": 58100,
                      "name": "现场",
                      "alg": null
                  },
                  {
                      "id": 9102,
                      "name": "演唱会",
                      "alg": null
                  },
                  {
                      "id": 57105,
                      "name": "粤语现场",
                      "alg": null
                  },
                  {
                      "id": 57108,
                      "name": "流行现场",
                      "alg": null
                  },
                  {
                      "id": 1100,
                      "name": "音乐现场",
                      "alg": null
                  },
                  {
                      "id": 5100,
                      "name": "音乐",
                      "alg": null
                  }
              ],
              "previewUrl": "http://vodkgeyttp9.vod.126.net/vodkgeyttp8/preview_107161222_t9qmzDnc.webp?wsSecret=3b74bd8cc26d1cd2b1b549f0453a1c5a&wsTime=1677409840",
              "previewDurationms": 4000,
              "hasRelatedGameAd": false,
              "markTypes": null,
              "relateSong": [],
              "relatedInfo": null,
              "videoUserLiveInfo": null,
              "vid": "8F9BB19518CBFA14708BD4641DBB7A9A",
              "durationms": 421130,
              "playTime": 6439197,
              "praisedCount": 30172,
              "praised": false,
              "subscribed": false
          },
          "id": "8F9BB19518CBFA14708BD4641DBB7A9A",
          "url": "http://vodkgeyttp9.vod.126.net/vodkgeyttp8/41X4zD7v_107161222_shd.mp4?ts=1677413441&rid=D180765541F90BA045005389510FCD97&rl=3&rs=tFXgwJnPwcwZWdlqSeRYtoyKojiVRKlK&sign=de7d1d509a0caefbfdc485bdc8f9d83f&ext=%2FOIbZbadGXOxUwEwUpe5lcOmKcsflJQ4uu362YdMwFHsNDNEt%2BpGMHpHJ9AenEi7IfMhT1dfaNX8Wl6ZwhSB9lMTZXCRcVcDU7YyLbfQQpJ5kV4iRio7mkcQIL2f6MsgqK4t3o0rYXv5%2BxoSDgF%2FFEydJvxU4095otogGMwnGfwKxgaLhiS4fHTXhxo4aTafkaIXxB8DC99UXbfIqBVW0UAt1Ul%2BR76iDr88zDCsrBdk1IiSxlK%2F4AfCQsM0x0IK"
      }
    ];

    let  {videoList} = this.data;
    //将视频最新数据更新到原有列表区域
    videoList.push(...newVideoList);
    this.setData({
      videoList
    })
  },

  // 跳转至搜索界面
  toSearch(){
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage({from}) {
    console.log(from,123)
    if(from === 'button'){
      return {
        title: '来自button的转发',
        page: '/pages/video/video',
        imageUrl: '/static/images/nvsheng.jpg'
      }
    }else {
      return {
        title: '来自menu的转发',
        page: '/pages/video/video',
        imageUrl: '/static/images/nvsheng.jpg'
      }
    }
  }
})